from network_manager import PortManager
import os


class DockerRedisTask():
    def __init__(self, file_path, port_manager):
        self.source_file_path = "docker_redis_sample/"
        self.target_file_path = file_path
        self.port_manager = port_manager


    def start(self):
        if not os.path.exists(self.target_file_path):
            os.system("mkdir " + self.target_file_path)
        self.create_server()
        self.create_requirements()
        self.create_dockerfile()
        self.create_docker_compose_yaml()
        os.system("cd " + self.target_file_path + " && docker-compose up -d")


    def stop(self):
        os.system("cd " + self.target_file_path + " && docker-compose stop")


    def create_server(self):
        file_name = "app.py"
        file_content = self.read_to_program(self.source_file_path + file_name)
        self.write_to_file(self.target_file_path + file_name, file_content)


    def create_requirements(self):
        file_name = "requirements.txt"
        file_content = self.read_to_program(self.source_file_path + file_name)
        self.write_to_file(self.target_file_path + file_name, file_content)


    def create_dockerfile(self):
        file_name = "Dockerfile"
        file_content = self.read_to_program(self.source_file_path + file_name)
        self.write_to_file(self.target_file_path + file_name, file_content)


    def create_docker_compose_yaml(self):
        file_name = "docker-compose.yml"
        file_content = self.read_to_program(self.source_file_path + file_name)
        file_content = file_content.replace("host_port", str(self.port_manager.assign()))

        self.write_to_file(self.target_file_path + file_name, file_content)


    def read_to_program(self, file_name):
        with open(file_name) as f:
            file_content = f.read()
        return file_content


    def write_to_file(self, file_name, file_content):
        with open(file_name, "w") as f:
            f.write(file_content)